//
//  VOLMyJourneyViewController.m
//  Volver
//
//  Created by administrator on 14-10-17.
//  Copyright (c) 2014年 vol. All rights reserved.
//

#import "VOLMyJourneyViewController.h"

#import "common.h"
#import "HTTPDefine.h"

#import "REFrostedViewController.h"
#import "ASIHTTPRequest.h"
#import "JSONKit.h"
#import "MBProgressHUD.h"
#import "MJRefresh.h"

#import "VOLAppDelegate.h"
#import "VOLMyJourneyCell.h"
#import "VOLMyJourneyCellModel.h"
#import "VOLOrderFormInfoViewController.h"
#import "VOLHistoryOrderFormViewController.h"

@interface VOLMyJourneyViewController ()
{
    VOLAppDelegate *del;
    JSONDecoder *jd;
    MBProgressHUD *HUD;
    NSFileManager *manager;
    
    NSDateFormatter *formatter;
    //用来保存数据源的数组
    NSMutableArray *myJourneyData;
    
    //当前时间
    double currentTime;
}

@end

@implementation VOLMyJourneyViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //初始化一些对象
    del = kGetDel;
    jd = [[JSONDecoder alloc] init];
    manager = [NSFileManager defaultManager];
    //初始化房源数组
    myJourneyData = [NSMutableArray array];
    //初始化formatter
    formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy年MM月dd日"];
    
    
    //添加标题
    self.title = @"我的旅程";
    
    //添加菜单按钮
    addLeftNavigationBarButton();
    
    //添加“历史”按钮
    UIBarButtonItem *right = [[UIBarButtonItem alloc] initWithTitle:@"历史" style:UIBarButtonItemStylePlain target:self action:@selector(goToHistory:)];
    right.tintColor = kThemeColor;
    self.navigationItem.rightBarButtonItem = right;
    
    //将noticeLabel隐藏，当需要显示时再显示出来
    self.noticeLabel.hidden = YES;
    
    //当前日期
    NSString *nowStr = [formatter stringFromDate:[NSDate date]];
    NSDate *currentDate = [formatter dateFromString:nowStr];
    currentTime = [currentDate timeIntervalSince1970];
    
    //添加上拉下拉；
    [self setupRefresh];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 进入界面时刷新
-(void)viewWillAppear:(BOOL)animated{
    if (del.isRefresh == 0) {//当不是从菜单栏或者发布成功时跳转过来的不用刷新
        return;
    }
    
    if (del.isRefresh == 4) {//从菜单栏跳转
        HUD = [[MBProgressHUD alloc] initWithView:self.view];
        [self.view addSubview:HUD];
        [HUD showAnimated:YES whileExecutingBlock:^{
            //将是否刷新再置为0
            del.isRefresh = 0;
            [self loadMyJourneyDate];
        } completionBlock:^{
            [HUD removeFromSuperview];
            HUD = nil;
        }];
    }
    else{
        //将是否刷新再置为0
        del.isRefresh = 0;
        
        //开始刷新
        [self.tableView headerBeginRefreshing];
    }
    
}

#pragma mark - 其它方法
#pragma mark - 设置上拉、下拉
- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [self.tableView addHeaderWithTarget:self action:@selector(mjHeaderRereshing)];
    
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    //    [self.tableView addFooterWithTarget:self action:@selector(footerRereshing)];
    
    // 设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
    self.tableView.headerPullToRefreshText = @"下拉刷新";
    self.tableView.headerReleaseToRefreshText = @"松开马上刷新了";
    self.tableView.headerRefreshingText = @"拼命加载中...";
    
}

#pragma mark - 下拉刷新时调用的方法
-(void)mjHeaderRereshing{
    //加载数据，用异步方式
    [self loadMyJourneyDate];
    
}

#pragma mark - 按钮点击事件
#pragma mark 菜单点击按钮
-(void)showMenu:(id)sender{
    kActionOfMenuButton;
}


#pragma mark 跳转“历史记录界面”
-(void)goToHistory:(id)sender{
    VOLHistoryOrderFormViewController *historyVC = [self.storyboard instantiateViewControllerWithIdentifier:@"historyOrderFormController"];
    del.isRefresh = 20;
    [self.navigationController pushViewController:historyVC animated:YES];
}

#pragma mark - 加载数据
#pragma mark 异步请求加载订单数据
-(void)loadMyJourneyDate{
    //使用异步请求加载
    
    //发送异步请求
    
    //获取当前时间并转化为double
    double now = kGetCurrentTime;
    NSString *urlstr = [NSString stringWithFormat:@"%@orderform/searchAllUnfinishOrderFormsByUserID?userID=%d&today=%f",kHTTPHome,del.currentUser.userID,now];
    NSURL *url = [NSURL URLWithString:urlstr];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    //设置代理
    request.delegate = self;
    [request startAsynchronous];
    
}



#pragma mark 加载图片
-(void)loadImage:(NSString *)imageName houseID:(int)houseID indexPath:(NSIndexPath *)indexPath imagePath:(NSString *)imagePath{
    
    //开启新线程加载图片
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //组装image的url
        NSString *urlstr = [NSString stringWithFormat:@"%@%d/%@",kHouseImageHome,houseID,imageName];
        NSURL *url = [NSURL URLWithString:urlstr];
        NSData *data = [NSData dataWithContentsOfURL:url];
        UIImage *image = [UIImage imageWithData:data];
        if (image !=nil) {
            dispatch_async(dispatch_get_main_queue(), ^{
                VOLMyJourneyCell *cell = (VOLMyJourneyCell *)[self.tableView cellForRowAtIndexPath:indexPath];
                cell.houseImage.image = image;
                //本地保存图片
                [data writeToFile:imagePath atomically:YES];
            });
        }
        else{
            NSLog(@"没有图片");
        }
    });
    
}


#pragma mark - 代理方法

#pragma mark - 异步请求代理
#pragma mark 请求成功
-(void)requestFinished:(ASIHTTPRequest *)request{
    //得到返回数据
    NSData *data = [request responseData];
    if (data == nil) {
        NSLog(@"myJourney------data为空");
        return;
    }
    
    NSDictionary *dic = [jd objectWithData:data];
    int result = [[dic objectForKey:@"result"] intValue];
    if (result == 0) {
        //如果没有订单，直接清空数组
        [myJourneyData removeAllObjects];
        NSLog(@"myJourney-----没有订单");
    }
    else{
        //首先判断myJourneyData是否为空，如果不是，先清空
        if (myJourneyData.count != 0) {
            [myJourneyData removeAllObjects];
        }
        //得到订单数组
        NSArray *array = [dic objectForKey:@"orderForms"];
        
        //遍历这个数组
        for (NSDictionary *obj in array) {
            VOLMyJourneyCellModel *model = [[VOLMyJourneyCellModel alloc] init];
            model.orderFormID = [[obj objectForKey:@"of_id"] intValue];
            model.houseID = [[obj objectForKey:@"house_id"] intValue];
            model.arriveDate = [[obj objectForKey:@"arrive_date"] doubleValue];
            
            //房屋标题和地址
            model.houseTitle = [obj objectForKey:@"house_title"];
            //获取房屋地址
            NSString *province = [obj objectForKey:@"house_province"];
            NSString *city = [obj objectForKey:@"house_city"];
            NSString *street = [obj objectForKey:@"house_street"];
            model.houseAddress = [NSString stringWithFormat:@"%@%@%@",province,city,street];
            
            model.houseImageName = [obj objectForKey:@"image_name"];
            
            //将model加入到myJourneyData
            [myJourneyData addObject:model];
        }
    }
    
    
    
    //数组遍历完毕，更新主界面
    //判断是否有收藏的房屋
    if (myJourneyData.count == 0) {
        //显示提示Label
        self.noticeLabel.text = @"您还没有预订房屋";
        self.noticeLabel.textColor = kThemeColor;
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        self.noticeLabel.hidden = NO;
    }else{
        self.noticeLabel.hidden = YES;
    }
    
    //刷新tableView
    [self.tableView reloadData];
    
    //停止刷新动作
    [self.tableView headerEndRefreshing];
}


#pragma mark 请求失败
-(void)requestFailed:(ASIHTTPRequest *)request{
    //停止刷新动作
    [self.tableView headerEndRefreshing];
    NSLog(@"myJourney-----请求失败");
}



#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return myJourneyData.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"myJourneyCell";
    VOLMyJourneyCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    
    // Configure the cell...
    //设置cell上Label的字体颜色
    cell.houseAddressLabel.textColor = kPriceLabelColor;
    
    //取得数据模式
    VOLMyJourneyCellModel *model = myJourneyData[indexPath.row];
    cell.houseTitleLabel.text = model.houseTitle;
    if (model.arriveDate < currentTime) {
        cell.arriveDateLabel.textColor = [UIColor redColor];
        cell.cellNoticeLabel.textColor = [UIColor redColor];
        cell.cellNoticeLabel.text = @"未入住";
        cell.cellNoticeLabel.hidden = NO;
    }else{
        cell.arriveDateLabel.textColor = kOrangeColor;
        cell.cellNoticeLabel.hidden = YES;
    }
    NSString *dateStr = [formatter stringFromDate:kTransformToDate(model.arriveDate)];
    cell.arriveDateLabel.text = [NSString stringWithFormat:@"%@",dateStr];
    cell.houseAddressLabel.text = model.houseAddress;
    
    //加载图片
    //先判断是否有这个路径存在，如果没有要先创建
    NSString *imageDocumentPath = [NSString stringWithFormat:@"%@%d/houseImages/%d",kGetDocumentsPath,del.currentUser.userID,model.houseID];
    if (![manager fileExistsAtPath:imageDocumentPath]) {
        [manager createDirectoryAtPath:imageDocumentPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    //先从本地查找是否已有图片
    NSString *imagePath = [NSString stringWithFormat:@"%@%d/houseImages/%d/%@",kGetDocumentsPath,del.currentUser.userID,model.houseID,model.houseImageName];
    if ([manager fileExistsAtPath:imagePath]) {
        cell.houseImage.image = [UIImage imageWithContentsOfFile:imagePath];
    }
    else{
        //若不存在，调用方法下载图片
        [self loadImage:model.houseImageName houseID:model.houseID indexPath:indexPath imagePath:imagePath];
    }
    
    return cell;
}

#pragma mark 行高
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 105;
}

#pragma mark 点击cell时
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    //跳转
    VOLOrderFormInfoViewController *orderFormInfo = [self.storyboard instantiateViewControllerWithIdentifier:@"orderFormInfoController"];
    orderFormInfo.receiveModel = myJourneyData[indexPath.row];
    orderFormInfo.sourceFrom = 25;
    [self.navigationController pushViewController:orderFormInfo animated:YES];
}

@end





